#!/bin/bash
#自动化安装k8s集群

# 传参检测
[ $# -ne 5 ] && echo -e "Usage: $0 密码 所有主机网段 所有主机网络位  docker镜像仓库 deploy_host k8s-cluster-name\nExample: bash $0 1 192.168.1 30\ 31\ 32\ 33 192.168.1.34  192.168.1.30 k8s_cluster\n" && exit 11 

#定义变量
export release=3.0.0
export k8s_ver=v.1.20.2  # v1.20.2, v.1.19.7, v1.18.15, v1.17.17
passwd=$1
netnum=$2
nethosts=$3
cri=docker
cni=flannel
export registry=$4
deploy_host=$5
clustername=$6


#测试环境
echo "-------------------------  基础环境测试   ---------------------------"
[ Permissive == `getenforce` ] && echo -e "\033[32m selinux已禁止 \033[0m" ||echo -e "\033[31m selinux为禁止 \033[0m"
[ 0B == `free -h |awk '/Swap/{print $2}'` ] && echo -e "\033[32m Swap已禁止 \033[0m" ||echo -e "\033[31m Swap未禁止 \033[0m"
[ inactive == `systemctl status firewalld.service |awk '/Active/{print $2}'` ] && echo -e "\033[32m firewalld已关闭 \033[0m" ||echo -e "\033[31m firewalld未关闭 \033[0m"


echo "-------------------------  ssh免密登录 ---------------------------"
# 在deploy机器做其他node的ssh免密操作
for host in `echo "${nethosts}"`
do
    echo "============ ${netnum}.${host} ===========";
if [[ ${USER} == 'root' ]];then
        [ ! -f /${USER}/.ssh/id_rsa ] &&\
        ssh-keygen -t rsa -P '' -f /${USER}/.ssh/id_rsa
    else
        [ ! -f /home/${USER}/.ssh/id_rsa ] &&\
        ssh-keygen -t rsa -P '' -f /home/${USER}/.ssh/id_rsa
    fi
    sshpass -p ${passwd} ssh-copy-id -o StrictHostKeyChecking=no ${USER}@${netnum}.${host}
done

echo "-------------------------  测试主机网络状态 ---------------------------"
for host in `echo "${nethosts}"`
do
    echo "============ ${netnum}.${host} ===========";
ssh -o StrictHostKeyChecking=no ${USER}@${netnum}.${host} ping -c 3 www.baidu.com &>/dev/null
[ $? -eq 0 ] && echo  -e "\033[32m ${netnum}.${host} 网络正常\033[0m" ||echo  -e "\033[31m ${netnum}.${host} 网络异常\033[0m"
done


echo "-------------------------  配置deploy主机yum源 ---------------------------"
wget -O  /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
wget https://mirror.webtatic.com/yum/el7/epel-release.rpm $>/dev/null
rpm -ivh  epel-release.rpm $>/dev/null

#参考文档 http://docs.kubernetes.org.cn/457.html,官方网址国内 无法访问，使用腾讯云
cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.cloud.tencent.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
enabled=1
gpgcheck=0
EOF

systemctl enable kubelet && systemctl start kubelet
yum makecache ;yum repolist &>/dev/null
[ $? -eq 0 ] &&  echo  -e "\033[32m ${deploy_host} \033[0m" ||echo  -e "\033[31m ${netnum}.${host} 网络异常\033[0m"


echo "------------------------- 安装k8s相关组件 ---------------------------"
echo "============== 安装docker,kubelet ,kubeadm,kubectl =============="
yum -y install docker-ce  kubelet kubeadm kubuctl ansible
 if  [ $? -eq 0 ];then 
echo -e "\033[32m  k8s组件安装成功，是否安装私有镜像仓库（yes/no）\033[0m"
else
echo  -e "\033[31m   k8s组件安装失败 \033[0m" 
exit
fi
read -p "" oh
case $oh in
yes|Yes|YES)
cd ansible
ansible all -m ping
[ $? -eq 0 ]&& ansible-playbook registry_install.yaml ||exit ;;
no|No|NO)
  exit ;;
*)
echo  -e "\033[31m 必须先安装镜像仓库 \033[0m"
esac

echo "------------------------- 准备相对应的配置文件 ---------------------------"
mkdir -p /etc/docker
cat <<EOF > /etc/docker/daemon.json 
 {
    "exec-opts": ["native.cgroupdriver=systemd"],
    "registry-mirrors": ["https://hub-mirror.c.163.com"],
    "insecure-registries":["$registry:5000", "registry:5000"]
}
EOF
systemctl enable --now docker kubelet
docker info |grep Cgroup
cat <<EOF >  /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
EOF
modprobe br_netfilter
sysctl --system
echo "------------------------- 导入镜像到私有仓库 ---------------------------"
#镜像尚未找到.....

for i in *.tar.gz;do docker load -i ${i};done

docker images
docker images |awk '$2!="TAG"{print $1,$2}'|while read _f _v;do
    docker tag ${_f}:${_v} ${registry}:5000/${_f##*/}:${_v}; 
    docker push ${registry}:5000/${_f##*/}:${_v}; 
    docker rmi ${_f}:${_v}; 
done
curl http://${registry}:5000/v2/_catalog
echo "------------------------设置kubuctl kubuadm自动补齐 ---------------------------"
bash
kubectl completion bash >/etc/bash_completion.d/kubectl
kubeadm completion bash >/etc/bash_completion.d/kubeadm
exit
echo "-----------------------ipvs代理 ---------------------------"
yum install -y ipvsadm ipset
echo "-----------------------测试安装k8s---------------------------"
kubeadm init --dry-run
 if  [ $? -eq 0 ];then 
echo -e "\033[32m  测试安装成功\033[0m"
else
echo  -e "\033[31m  测试安装失败  \033[0m" 
exit
fi

echo "-----------------------部署kubeadm---------------------------"
cd ~/k8s/init
read -p "确认该目录的文件是否根据实际情况更改（yes/on）" oh
case $oh in
yes|Yes|YES)
 kubeadm init --config=kubeadm-init.yaml |tee master-init.log
[ $? -eq 0 ]&&  echo  -e "\033[32m kubeadm部署成功 \03
[0m" ||exit 
mkdir -p $HOME/.kube
cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
chown $(id -u):$(id -g) $HOME/.kube/config;;
no|No|NO)
  exit ;;
*)
echo  -e "\033[31m 必须确认文件是否根据实际情况更改 \033[0m"
esac

echo "-----------------------验证部署结果---------------------------"
kubectl version
kubectl get componentstatuses